package com.base.cn.platform.os.controller.op.giftcard;

import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.FileExportImportUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.entity.op.giftcard.OpGiftCard;
import com.base.cn.platform.os.entity.op.giftcard.OpGiftCardCode;
import com.base.cn.platform.os.service.op.giftcard.OpGiftCardBiz;
import com.base.cn.platform.os.service.op.giftcard.OpGiftCardCodeBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 礼品卡
 * @author ll
 * @date 2018/5/14 9:16
 */
@RestController
@RequestMapping("/manage/op")
public class OpGiftCardController extends BaseController {

    @Autowired
    private OpGiftCardBiz opGiftCardBiz;
    @Autowired
    private OpGiftCardCodeBiz opGiftCardCodeBiz;

    /**
     * 搜索礼品卡列表
     * @param giftCard
     * @return
     */
    @RequestMapping("/queryGiftCardListPage")
    public PageInfo<OpGiftCard> queryGiftCardListPage(@RequestParam(value = "currentPage",required = false,defaultValue = "1")Integer currentPage,
                                                     @RequestBody OpGiftCard giftCard,
                                                     @RequestParam(value = "courseData",required = false,defaultValue = "false")boolean courseData){
        Pagination page =new Pagination();
        page.setCurrentPage(currentPage);
        return opGiftCardBiz.queryGiftCardListPage(page,giftCard,courseData);
    }

    /**
     * 添加礼品卡
     * @param giftCard
     * @return
     */
    @RequestMapping("/saveGiftCard")
    public Map<String,Object> saveGiftCard(@RequestBody OpGiftCard giftCard){
        if(!ObjectUtils.isNotEmpty(giftCard)){
            return ResultUtil.ERROR("请填写礼品卡数据");
        }
        if(giftCard.getCardType()==null||giftCard.getCardType()<=0){
            return ResultUtil.ERROR("请选择礼品卡类型");
        }
        if(StringUtils.isEmpty(giftCard.getCardName())){
            return  ResultUtil.ERROR("请填写礼品卡名称");
        }
        if (giftCard.getGenNum()==null||giftCard.getGenNum()<=0){
            return ResultUtil.ERROR("请填写礼品卡生成数量");
        }
        if(giftCard.getGenNum()>10000){
            return  ResultUtil.ERROR("礼品卡生成数量最多只能为10000");
        }
        if(giftCard.getCardType()==3 && (giftCard.getAmount()==null||giftCard.getAmount()<=0.0)){
            return  ResultUtil.ERROR("请填写礼品卡价值金额");
        }
        if(giftCard.getCardType()==3&&!StringUtils.isDigit(giftCard.getAmount().toString())){
            return   ResultUtil.ERROR("请正确填写礼品卡价值金额");
        }
        if (giftCard.getCardType()==2&&StringUtils.isEmpty(giftCard.getCourseIds())){
            return   ResultUtil.ERROR("请选择课程");
        }
        if(giftCard.getTimeType()==1){
            if (giftCard.getBeginTime()==null||giftCard.getBeginTime().equals("")){
                return  ResultUtil.ERROR("请填写开始时间");
            }
            if(giftCard.getEndTime()==null||giftCard.getEndTime().equals("")){
                return  ResultUtil.ERROR("请填写结束时间");
            }
        }else{
            if(giftCard.getTimeDays()==null||giftCard.getTimeDays()<=0){
                return  ResultUtil.ERROR("请填写过期天数");
            }
            if(!StringUtils.isNumber(giftCard.getTimeDays().toString())){
                return  ResultUtil.ERROR("请正确填写过期天数");
            }
        }
        if(StringUtils.isEmpty(giftCard.getDepict())){
            return  ResultUtil.ERROR("请填写礼品卡描述");
        }
        OpGiftCard _giftCard =opGiftCardBiz.tx_saveGiftCard(giftCard);
        return ResultUtil.SUCCESS("添加成功",_giftCard);
    }


    /**
     * 批量删除 ， 冻结 ， 恢复 ，发布
     * @param giftCardIds
     * @param status
     * @return
     */
    @RequestMapping("/updateStatusByIds")
    public Map<String,Object>  updateStatusByIds(@RequestParam("giftCardIds")String giftCardIds,
                                                 @RequestParam("status")Integer status){
        opGiftCardBiz.updateStatusByIds(giftCardIds,status);
        return ResultUtil.SUCCESS("操作成功");
    }

    /**
     * 查看详情页面
     * @param giftCardId 礼品卡Id
     * @return
     */
    @RequestMapping("/queryOpGiftCardById")
    public OpGiftCard queryOpGiftCardById(@RequestParam("giftCardId")BigDecimal giftCardId,
                                         @RequestParam(value = "courseData",required = false,defaultValue = "false")boolean courseData){
        return opGiftCardBiz.queryOpGiftCardById(giftCardId,courseData);
    }


    /**
     * 赠送GiftCard礼品卡
     * @param userIds
     * @return
     */
    @RequestMapping("/presentGiftCard")
    public Map<String,Object> presentGiftCard(@RequestParam("userIds")String userIds,
                                              @RequestParam("giftCardId")BigDecimal giftCardId){
        userIds = StringUtils.subHeadTailString(userIds,",");
        userIds = Stream.of(userIds.split(",")).filter(StringUtils::isNumber).collect(Collectors.joining(","));
        if (StringUtils.isEmpty(userIds)) {
            return ResultUtil.ERROR("请选择赠送的学员");
        }
        String[] splits = userIds.split(",");
        int count = splits.length;
        List<OpGiftCardCode> giftCardCodes = opGiftCardCodeBiz.queryOpGiftCardCodesByGiftCardIdAndStatusAndIsUserData(giftCardId,1,null,count);
        if (!ObjectUtils.isNotEmpty(giftCardCodes)) {
            return ResultUtil.ERROR("选择的礼品卡已无可赠数量");
        }
        if(giftCardCodes.size() >= count){
            for(int  i=0;i<count;i++){
                if(giftCardCodes.get(i).getTimeType()==2){
                    Date date = new Date();
                    Date endTime = DateUtils.addByDate(date, Calendar.DAY_OF_MONTH,giftCardCodes.get(i).getTimeDays());
                    giftCardCodes.get(i).setBeginTime(date);
                    giftCardCodes.get(i).setEndTime(endTime);
                }
                giftCardCodes.get(i).setUserId(new BigDecimal(splits[i]));
            }
        }else{
            return ResultUtil.ERROR("选择用户超过礼品卡总量");
        }
        opGiftCardBiz.presentGiftCard(giftCardCodes);
        return ResultUtil.SUCCESS("礼品卡赠送成功");
    }

    @RequestMapping("/downloadExcelGiftCardList")
   public ResponseEntity<byte[]> downloadExcelGiftCardList(@RequestParam(value = "giftCardId") BigDecimal giftCardId, @RequestParam(value = "useType",required = false) Integer useType) throws IOException{

        String [] titles = {"ID","礼品卡名称","礼品卡类型","有效时间","礼品卡编码","礼品卡密码","状态","使用时间","持有用户","手机号"};
        OpGiftCard opGiftCard = opGiftCardBiz.queryOpGiftCardById(giftCardId, true);
        OpGiftCardCode opGiftCardCode = new OpGiftCardCode();
        opGiftCardCode.setGiftCardId(giftCardId);
        if(ObjectUtils.isNotEmpty(useType)){
            opGiftCardCode.setUseType(useType);
        }
        List<OpGiftCardCode> opGiftCardCodes = opGiftCardCodeBiz.queryOpGiftCardCodeList(opGiftCardCode, false, true, false);
        return FileExportImportUtil.exportExcel(titles, getData(opGiftCard,opGiftCardCodes),opGiftCard.getCardName()+"_礼品卡");
    }


    private  List<List<String>> getData(  OpGiftCard opGiftCard, List<OpGiftCardCode> opGiftCardCodes){
        List<List<String>> lists = new ArrayList<List<String>>();
        if(ObjectUtils.isNotEmpty(opGiftCard)){
            //有效期
            String periodValidity ="";
            if(opGiftCard.getTimeType()==1){
                periodValidity= DateUtils.format(opGiftCard.getBeginTime())+"——"+DateUtils.format(opGiftCard.getEndTime());

            }else{
                periodValidity=opGiftCard.getTimeDays()+"天";
            }
            //礼卡类型，1学员卡，2课程卡，3充值卡
            String cardType ="";
            switch (opGiftCard.getCardType()){
                case 1:
                    cardType ="学员卡";
                    break;
                case 2:
                    cardType ="课程卡";
                    break;
                case 3:
                    cardType ="充值卡";
                    break;
            }
            if (ObjectUtils.isNotEmpty(opGiftCardCodes)) {
                String finalPeriodValidity = periodValidity;
                String finalCardType = cardType;
                opGiftCardCodes.forEach(v -> {
                    String useType ="";
                    Map<String, Object> user = v.getUser();
                    switch (v.getUseType()){
                        case 1:
                            useType ="未使用";
                            break;
                        case 2:
                            useType ="已使用";
                            break;

                    }
                    lists.add(Arrays.asList(
                            v.getId().toString(),
                            opGiftCard.getCardName(),
                            finalCardType,
                            finalPeriodValidity,
                            v.getCode(),
                            v.getCodePwd(),
                            useType,
                            finalPeriodValidity,
                            ObjectUtils.isNotEmpty(user)?user.get("nickname").toString():"",
                            ObjectUtils.isNotEmpty(user)?ObjectUtils.isNotEmpty(user.get("mobile"))?user.get("mobile").toString():"":""

                    ));

                });
            }

        }
        return  lists;
    }
}
